<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\web\controller;

use app\common\model\UserFavorite;
use app\common\model\UserLevel;
use app\common\model\UserSignLog as UserSign;
use app\common\model\Goods;
use app\common\model\UserVip;

class User extends Base
{
    private function requireLogin()
    {
        if ($this->user_id <= 0) {
            if ($this->request->isAjax()) {
                return $this->error('请先登录');
            } else {
                return redirect('/user/login');
            }
        }
        return true;
    }

    /**
     * 用户中心首页
     */
    public function index()
    {
        $result = $this->requireLogin();
        if ($result instanceof \support\Response) {
            return $result;
        }
        // 模板渲染已自动获取用户信息
        return $this->render('user/index', [
            'title' => '用户中心',
        ]);
    }

    /**
     * 我的订单
     */
    public function order()
    {
        $result = $this->requireLogin();
        if ($result instanceof \support\Response) {
            return $result;
        }

        $page  = (int) $this->request->get('page', 1);
        $limit = 5;

        // 使用用户模型的关联方法获取订单列表
        $orders = $this->user->orders()->order("id desc")->paginate($limit, false, ['page' => $page]);

        // 计算总页数
        $totalPages = $orders->total() > 0 ? ceil($orders->total() / $limit) : 1;

        return $this->render('user/order', [
            'title'        => '我的订单',
            'orders'       => $orders->items(),
            'total'        => $orders->total(),
            'current_page' => $page,
            'per_page'     => $limit,
            'total_pages'  => $totalPages,
        ]);
    }

    /**
     * 我的收藏
     */
    public function favorite()
    {
        $result = $this->requireLogin();
        if ($result instanceof \support\Response) {
            return $result;
        }

        $page  = (int) $this->request->get('page', 1);
        $limit = 10;

        // 直接使用用户模型的关联方法获取收藏列表
        $favorites = $this->user->favoritedGoods()
            ->order('id desc')
            ->paginate($limit)
            ->each(function ($item) {
                $item->goods_image = $item->slider_image[0] ?? '';
                // 商品收藏时间 而非商品添加时间
                $item->create_time = UserFavorite::where('relation_id', $item->id)->where('type', 1)->value('create_time');
            });

        // 计算总页数
        $totalPages = $favorites->total() > 0 ? ceil($favorites->total() / $limit) : 1;

        return $this->render('user/favorite', [
            'title'        => '我的收藏',
            'favorites'    => $favorites->items(),
            'total'        => $favorites->total(),
            'current_page' => $page,
            'per_page'     => $limit,
            'total_pages'  => $totalPages,
        ]);
    }

    /**
     * 获取商品信息
     */
    private function getGoodsInfo($goodsId)
    {
        // 这里应该调用商品API获取详情，暂时返回模拟数据
        return [
            'id'          => $goodsId,
            'name'        => '商品名称 ' . $goodsId,
            'price'       => 99.9,
            'image'       => '/static/images/placeholder.png',
            'description' => '商品描述',
            'status'      => 1,
        ];
    }

    /**
     * 会员等级
     */
    public function level()
    {
        $result = $this->requireLogin();
        if ($result instanceof \support\Response) {
            return $result;
        }

        // 获取所有会员等级
        $allLevels = UserLevel::getEnabledLevels();

        // 为每个等级添加权益信息
        foreach ($allLevels as &$level) {
            $level['benefits'] = $this->getLevelBenefits($level);
        }

        // 获取当前会员等级
        $currentLevel = $this->user->level;
        if ($currentLevel) {
            $currentLevel             = $currentLevel->toArray();
            $currentLevel['benefits'] = $this->getLevelBenefits($currentLevel);
        }

        // 获取下一个等级信息
        $nextLevel          = null;
        $progressPercentage = 0;
        $needPoints         = 0;

        if ($currentLevel) {
            $nextLevel = UserLevel::getNextLevel($currentLevel['id']);
            if ($nextLevel) {
                $nextLevel['benefits'] = $this->getLevelBenefits($nextLevel);

                // 计算升级进度百分比
                $userPoints       = $this->user->points ?? 0;
                $currentMinPoints = $currentLevel['min_points'] ?? 0;
                $nextMinPoints    = $nextLevel['min_points'] ?? 1000;

                if ($nextMinPoints > $currentMinPoints) {
                    $progressPercentage = (($userPoints - $currentMinPoints) / ($nextMinPoints - $currentMinPoints)) * 100;
                    $progressPercentage = max(0, min(100, $progressPercentage)); // 限制在0-100之间
                }

                $needPoints = max(0, $nextMinPoints - $userPoints);
            }
        }

        // 准备数据
        $levelData = [
            'user'                => $this->user,
            'all_levels'          => $allLevels,
            'current_level'       => $currentLevel,
            'next_level'          => $nextLevel,
            'progress_percentage' => round($progressPercentage, 1),
            'need_points'         => $needPoints,
        ];

        return $this->render('user/level', [
            'title'      => '会员等级',
            'level_data' => $levelData,
        ]);
    }

    /**
     * VIP会员
     */
    public function vip()
    {
        $result = $this->requireLogin();
        if ($result instanceof \support\Response) {
            return $result;
        }

        // 获取VIP信息
        $vipInfo = $this->user->getVipInfo();

        // 获取所有VIP套餐
        $vipPackages = UserVip::getEnabledVips();

        // 获取支付网关
        $paymentChannels = (new \app\api\controller\Pay())->getPayChannelData();

        // 获取VIP权益列表
        $vipBenefits = $this->getVipBenefits();

        // 获取FAQ列表
        $faqList = $this->getVipFaqList();

        // 计算VIP剩余天数
        $expireDays    = 0;
        $vipExpireTime = null;

        // 获取当前有效的VIP记录
        $currentVipRecord = $this->user->currentVip();
        if ($currentVipRecord && $currentVipRecord->end_time) {
            $vipExpireTime = $currentVipRecord->end_time;
            $expireTime    = strtotime($currentVipRecord->end_time);
            $currentTime   = time();
            $expireDays    = max(0, ceil(($expireTime - $currentTime) / 86400));
        }

        // 确保用户对象包含正确的VIP状态和过期时间
        $userData                    = $this->user->toArray();
        $userData['is_vip']          = $this->user->isVip() ? 1 : 0;
        $userData['vip_expire_time'] = $vipExpireTime;

        return $this->render('user/vip', [
            'title'            => 'VIP会员',
            'user'             => $userData,
            'vip_info'         => $vipInfo,
            'vip_packages'     => $vipPackages,
            'payment_channels' => $paymentChannels,
            'vip_benefits'     => $vipBenefits,
            'faq_list'         => $faqList,
            'expire_days'      => $expireDays,
        ]);
    }

    // ajax 获取支付渠道
    public function getPaymentChannels()
    {
        return $this->success('获取成功', (new \app\api\controller\Pay())->getPayChannelData());
    }

    /**
     * 每日签到
     */
    public function sign()
    {
        $result = $this->requireLogin();
        if ($result instanceof \support\Response) {
            return $result;
        }

        // 获取签到记录
        $month    = $this->request->get('month', date('Y-m'));
        $signLogs = UserSign::getUserMonthSignLogs($this->user_id, $month);

        // 获取连续签到天数
        $continuousDays = UserSign::getUserContinuousDays($this->user_id);

        // 检查今天是否已签到
        $todaySigned = UserSign::checkTodaySigned($this->user_id);

        // 获取签到规则
        $signRules = UserSign::getSignRules();

        // 增强签到规则数据，添加更多信息
        $enhancedSignRules = $this->enhanceSignRules($signRules);

        // 计算签到统计
        $signStats = $this->getSignStats($this->user_id, $month);

        // 计算今日可获得积分
        $todayPoints = $this->calculateTodayPoints($continuousDays, $todaySigned, $signRules);

        // 准备数据
        $signData = [
            'user'            => $this->user,
            'sign_logs'       => $signLogs,
            'continuous_days' => $continuousDays,
            'today_signed'    => $todaySigned,
            'sign_rules'      => $enhancedSignRules,
            'month'           => $month,
            'sign_stats'      => $signStats,
            'today_points'    => $todayPoints,
            'calendar_data'   => $this->generateCalendarData($signLogs, $month),
        ];

        return $this->render('user/sign', [
            'title'     => '每日签到',
            'sign_data' => $signData,
        ]);
    }

    /**
     * 购买VIP
     */
    public function buyVip()
    {
        $result = $this->requireLogin();
        if ($result instanceof \support\Response) {
            return $result;
        }

        if (!$this->request->isPost()) {
            return $this->error('请求方式错误');
        }

        // 检查登录
        if ($this->user_id <= 0) {
            return $this->error('请先登录');
        }

        $vip_id     = $this->request->post('vip_id');
        $channel_id = $this->request->post('channel_id');

        if (empty($vip_id)) {
            return $this->error('请选择VIP套餐');
        }

        $trade_no = UserVip::purchaseVip($this->user_id, $vip_id, $channel_id);
        if ($trade_no) {
            return $this->success('订单创建成功', [
                'order_id' => $trade_no,
                'pay_url'  => "/gopay?trade_no={$trade_no}",
            ]);
        } else {
            return $this->error('创建订单失败');
        }
    }

    /**
     * 检查支付状态
     */
    public function checkPaymentStatus()
    {
        $result = $this->requireLogin();
        if ($result instanceof \support\Response) {
            return $result;
        }

        if (!$this->request->isPost()) {
            return $this->error('请求方式错误');
        }

        $order_id = $this->request->post('order_id');
        if (empty($order_id)) {
            return $this->error('订单号不能为空');
        }

        // 查找VIP订单
        $vipRecord = \app\common\model\UserVipRecord::where('trade_no', $order_id)
            ->where('user_id', $this->user_id)
            ->find();

        if (!$vipRecord) {
            return $this->error('订单不存在');
        }

        // 检查支付状态
        $isPaid = $vipRecord->status == 1; // 1表示已支付

        return $this->success('查询成功', [
            'paid'         => $isPaid,
            'status'       => $vipRecord->status,
            'order_status' => $vipRecord->order_status
        ]);
    }

    /**
     * 收藏/取消收藏商品（AJAX接口）
     */
    public function toggleFavorite()
    {
        $result = $this->requireLogin();
        if ($result instanceof \support\Response) {
            return $result;
        }

        if (!$this->request->isPost()) {
            return $this->error('请求方式错误');
        }

        // 检查登录
        if ($this->user_id <= 0) {
            return $this->error('请先登录');
        }

        $goods_id = $this->request->post('goods_id', 0);

        if (empty($goods_id)) {
            return $this->error('参数错误');
        }

        // 验证商品是否存在
        $goods = Goods::where(['id' => $goods_id, 'status' => 1])->find();
        if (empty($goods)) {
            return $this->error('商品不存在或已下架');
        }

        // 切换收藏状态
        $result = UserFavorite::toggleFavorite($this->user_id, $goods_id, 1);

        if ($result['code'] == 1) {
            $message = $result['is_favorited'] ? '收藏成功' : '取消收藏成功';
            return $this->success($message, ['is_favorited' => $result['is_favorited']]);
        } else {
            return $this->error($result['msg'] ?? '操作失败，请稍后重试');
        }
    }

    /**
     * 添加收藏（AJAX接口）- 兼容旧接口
     */
    public function addFavorite()
    {
        return $this->toggleFavorite();
    }

    /**
     * 取消收藏（AJAX接口）- 兼容旧接口
     */
    public function removeFavorite()
    {
        return $this->toggleFavorite();
    }


    /**
     * 获取签到信息
     */
    private function getUserSign()
    {

        // 获取连续签到天数
        $continuousDays = UserSign::getUserContinuousDays($this->user_id);

        // 检查今天是否已签到
        $todaySigned = UserSign::checkTodaySigned($this->user_id);

        return [
            'today_signed'    => $todaySigned,
            'continuous_days' => $continuousDays,
        ];

    }

    /**
     * 取消订单（AJAX接口）
     */
    public function cancelOrder()
    {
        $result = $this->requireLogin();
        if ($result instanceof \support\Response) {
            return $result;
        }

        if (!$this->request->isPost()) {
            return $this->error('请求方式错误');
        }

        // 检查登录
        if ($this->user_id <= 0) {
            return $this->error('请先登录');
        }

        $trade_no = $this->request->post('trade_no');

        if (!$trade_no) {
            return $this->error('订单号不能为空');
        }


        // 使用用户模型的关联方法查找订单
        $order = $this->user->orders()->where([
            'trade_no' => $trade_no,
            'status'   => 0 // 只能取消未支付的订单
        ])->find();

        if (!$order) {
            return $this->error('订单不存在或无法取消');
        }

        $order->status = -1; // 设置为已取消
        $order->save();

        return $this->success('订单已取消');

    }


    /**
     * 退出登录
     */
    public function logout()
    {
        // 清除session
        session(['user_id' => null, 'user_token' => null]);

        // 返回JSON响应
        if (request()->isAjax()) {
            return json(['code' => 1, 'msg' => '退出成功']);
        }

        // 重定向到首页
        return redirect('/');
    }

    /**
     * 获取连续签到天数
     */
    private function getContinuousSignDays()
    {
        try {
            $signs = UserSign::where('user_id', $this->user_id)
                ->order('sign_date desc')
                ->limit(30)
                ->column('sign_date');

            if (empty($signs)) {
                return 0;
            }

            $days        = 0;
            $currentDate = date('Y-m-d');

            foreach ($signs as $signDate) {
                if ($signDate == $currentDate) {
                    $days++;
                    $currentDate = date('Y-m-d', strtotime($currentDate . ' -1 day'));
                } else {
                    break;
                }
            }

            return $days;
        } catch (\Exception $e) {
            return 0;
        }
    }

    /**
     * 获取用户等级信息
     */
    private function getUserLevel()
    {

        // 获取当前会员等级
        $currentLevel = $this->user->level;

        // 获取下一个等级信息
        $nextLevel = null;
        if ($currentLevel) {
            $nextLevel = UserLevel::getNextLevel($currentLevel->id);
        }

        return [
            'current_level' => $currentLevel,
            'next_level'    => $nextLevel,
        ];

    }

    /**
     * 获取用户VIP信息
     */
    private function getUserVip()
    {
        try {
            // 获取VIP信息
            $vipInfo = $this->user->getVipInfo();
            return $vipInfo;
        } catch (\Exception $e) {
            // 如果出错，使用默认数据
            return [
                'id'              => 0,
                'name'            => '普通用户',
                'expire_days'     => 0,
                'points_reward'   => 0,
                'vip_expire_time' => null,
            ];
        }
    }

    /**
     * 执行签到（AJAX接口）
     */
    public function doSign()
    {
        $result = $this->requireLogin();
        if ($result instanceof \support\Response) {
            return $result;
        }

        if (!$this->request->isPost()) {
            return $this->error('请求方式错误');
        }

        // 检查登录
        if ($this->user_id <= 0) {
            return $this->error('请先登录');
        }

        // 执行签到
        $result = $this->user->signIn();

        if ($result['code'] == 1) {
            return $this->success($result['msg'], $result['data']);
        } else {
            return $this->error($result['msg']);
        }
    }

    /**
     * 更新用户头像（AJAX接口）
     */
    public function updateAvatar()
    {
        $result = $this->requireLogin();
        if ($result instanceof \support\Response) {
            return $result;
        }

        if (!$this->request->isPost()) {
            return $this->error('请求方式错误');
        }

        $file = $this->request->file('file');
        if (!$file) {
            return $this->error('请上传头像');
        }

        if ($file && $file->isValid()) {
            $file_uri = '/avatar/' . $file->getUploadName();
            $file->move(public_path() . '/upload' . $file_uri);

            $avatar = conf('site_domain') . '/upload' . $file_uri;

            // 更新用户头像
            $this->user->avatar = $avatar;
            $this->user->save();

            return $this->success('头像更新成功', ['avatar' => $avatar]);
        } else {
            return $this->error('头像上传失败');
        }
    }

    /**
     * 修改用户昵称（AJAX接口）
     */
    public function updateNickname()
    {
        $result = $this->requireLogin();
        if ($result instanceof \support\Response) {
            return $result;
        }

        if (!$this->request->isPost()) {
            return $this->error('请求方式错误');
        }

        $nickname = $this->request->post('nickname', '');

        if (!$nickname) {
            return $this->error('请输入昵称');
        }

        // 更新昵称
        $this->user->nickname = $nickname;
        $this->user->save();

        return $this->success('昵称修改成功');
    }

    /**
     * 发送邮箱验证码（AJAX接口）
     */
    public function sendEmailCode()
    {
        if (!$this->request->isPost()) {
            return $this->error('请求方式错误');
        }

        $email      = $this->request->post('email', '');
        $type       = $this->request->post('type', 'bind'); // bind: 绑定邮箱, change_password: 修改密码, verify_old_email: 验证原邮箱
        $captcha    = $this->request->post('captcha', '');
        $captchaKey = $this->request->post('captcha_key', '');

        if (!$email) {
            return $this->error('请输入邮箱地址');
        }

        // 验证邮箱格式
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return $this->error('邮箱格式不正确');
        }

        // 验证图形验证码
        if (empty($captcha)) {
            return $this->error('请输入图形验证码');
        }

        if (empty($captchaKey)) {
            return $this->error('验证码已过期，请刷新');
        }

        // 验证图形验证码
        try {
            $captchaCheck = \Wangpeng1208\Captcha\Captcha::check($captcha, $captchaKey);
            if (!$captchaCheck) {
                return $this->error('图形验证码错误');
            }
        } catch (\Exception $e) {
            return $this->error('图形验证码验证失败');
        }

        // 如果是修改密码或验证原邮箱，需要验证是否为当前用户的邮箱
        if ($type === 'change_password' || $type === 'verify_old_email') {
            $result = $this->requireLogin();
            if ($result instanceof \support\Response) {
                return $result;
            }
            if ($this->user->email !== $email) {
                return $this->error('邮箱地址不正确');
            }
        }

        // 如果是绑定新邮箱，需要检查该邮箱是否已被其他用户使用
        if ($type === 'bind') {
            // 检查是否已经登录
            if ($this->user_id > 0) {
                // 检查邮箱是否已被其他用户使用
                $existUser = \app\common\model\User::where('email', $email)
                    ->where('id', '<>', $this->user_id)
                    ->find();

                if ($existUser) {
                    return $this->error('该邮箱已被其他用户使用');
                }
            }
        }

        // 检查发送频率限制
        $cacheKey = 'email_send_limit_' . $email;
        if (\support\Cache::get($cacheKey)) {
            return $this->error('发送过于频繁，请稍后再试');
        }

        // 生成验证码
        $code = str_pad(mt_rand(0, 999999), 6, '0', STR_PAD_LEFT);

        // 缓存验证码，5分钟有效
        \support\Cache::set('email_code_' . $email, $code, 300);

        // 设置发送频率限制，60秒内不能重复发送
        \support\Cache::set($cacheKey, 1, 60);

        try {
            (new \app\service\user\EmailMessageService())->send($email, '邮箱验证码', '您的验证码为：' . $code);
            return $this->success('验证码已发送到您的邮箱，请注意查收');
        } catch (\Exception $e) {
            return $this->error('验证码发送失败，请稍后重试');
        }
    }

    /**
     * 验证原邮箱（AJAX接口）
     */
    public function verifyOldEmail()
    {
        $result = $this->requireLogin();
        if ($result instanceof \support\Response) {
            return $result;
        }

        if (!$this->request->isPost()) {
            return $this->error('请求方式错误');
        }

        $code = $this->request->post('code', '');

        if (!$code) {
            return $this->error('请输入验证码');
        }

        // 验证邮箱是否存在
        if (!$this->user->email) {
            return $this->error('您当前未绑定邮箱');
        }

        // 验证邮箱验证码
        $cacheCode = \support\Cache::get('email_code_' . $this->user->email);
        if (!$cacheCode || $cacheCode != $code) {
            return $this->error('验证码错误或已过期');
        }

        // 清除验证码缓存
        \support\Cache::delete('email_code_' . $this->user->email);

        // 生成一个临时令牌，用于后续绑定新邮箱
        $token = md5($this->user->id . time() . uniqid());
        \support\Cache::set('change_email_token_' . $this->user->id, $token, 600); // 10分钟有效期

        return $this->success('原邮箱验证成功', ['token' => $token]);
    }

    /**
     * 绑定邮箱（AJAX接口）
     */
    public function bindEmail()
    {
        $result = $this->requireLogin();
        if ($result instanceof \support\Response) {
            return $result;
        }

        if (!$this->request->isPost()) {
            return $this->error('请求方式错误');
        }

        $email = $this->request->post('email', '');
        $code  = $this->request->post('code', '');
        $token = $this->request->post('token', ''); // 如果是修改邮箱，需要提供验证原邮箱的token

        if (!$email || !$code) {
            return $this->error('参数错误');
        }

        // 验证邮箱格式
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return $this->error('邮箱格式不正确');
        }

        // 如果用户已有邮箱，需要验证token
        if ($this->user->email && $email != $this->user->email) {
            $validToken = \support\Cache::get('change_email_token_' . $this->user->id);

            if (!$validToken || $validToken !== $token) {
                return $this->error('请先验证原邮箱');
            }

            // 验证通过后清除token
            \support\Cache::delete('change_email_token_' . $this->user->id);
        }

        // 验证邮箱是否已被使用
        $existUser = \app\common\model\User::where('email', $email)
            ->where('id', '<>', $this->user->id)
            ->find();

        if ($existUser) {
            return $this->error('该邮箱已被使用');
        }

        // 验证邮箱验证码
        $cacheCode = \support\Cache::get('email_code_' . $email);
        if (!$cacheCode || $cacheCode != $code) {
            return $this->error('验证码错误或已过期');
        }

        // 清除验证码缓存
        \support\Cache::delete('email_code_' . $email);

        // 更新邮箱
        $this->user->email = $email;
        $this->user->save();

        return $this->success('邮箱绑定成功');
    }

    /**
     * 修改密码（AJAX接口）
     */
    public function changePassword()
    {
        $result = $this->requireLogin();
        if ($result instanceof \support\Response) {
            return $result;
        }

        if (!$this->request->isPost()) {
            return $this->error('请求方式错误');
        }

        // 验证邮箱是否存在
        if (!$this->user->email) {
            return $this->error("请先绑定邮箱");
        }

        $code        = $this->request->post('code', '');
        $newPassword = $this->request->post('new_password', '');

        if (!$code || !$newPassword) {
            return $this->error('参数错误');
        }

        // 验证邮箱验证码
        $cacheCode = \support\Cache::get('email_code_' . $this->user->email);
        if (!$cacheCode || $cacheCode != $code) {
            return $this->error("验证码错误或已过期");
        }

        // 检查密码长度
        if (strlen($newPassword) < 6 || strlen($newPassword) > 20) {
            return $this->error("密码长度应为6-20个字符");
        }

        // 清除验证码缓存
        \support\Cache::delete('email_code_' . $this->user->email);

        // 更新密码
        $this->user->password = password_hash($newPassword, PASSWORD_DEFAULT);
        $this->user->save();

        return $this->success("密码修改成功");
    }

    /**
     * 获取图形验证码（AJAX接口）
     */
    public function getCaptcha()
    {
        try {
            // 使用 Wangpeng1208\Captcha\Captcha 生成验证码
            $captcha = \Wangpeng1208\Captcha\Captcha::base64();

            return $this->success('获取成功', [
                'key'    => $captcha['key'],
                'base64' => $captcha['base64']
            ]);
        } catch (\Exception $e) {
            return $this->error('生成验证码失败: ' . $e->getMessage());
        }
    }

    public function forgot()
    {
        // 重定向到Auth控制器的forgot方法
        return redirect('/user/forgot');
    }

    /**
     * 获取等级权益信息
     * @param array $level 等级信息
     * @return array
     */
    private function getLevelBenefits($level)
    {
        $benefits = [];

        // 根据等级名称或积分范围定义不同的权益
        $levelName = strtolower($level['name'] ?? '');
        $minPoints = $level['min_points'] ?? 0;

        // 基础权益（所有等级都有）
        $benefits[] = '基础浏览权限';
        $benefits[] = '评论互动功能';

        // 根据积分范围添加权益
        if ($minPoints >= 100) {
            $benefits[] = '高级内容访问';
            $benefits[] = '优先客服支持';
        }

        if ($minPoints >= 500) {
            $benefits[] = '专属内容推荐';
            $benefits[] = '无广告浏览';
        }

        if ($minPoints >= 1000) {
            $benefits[] = 'VIP专属活动';
            $benefits[] = '积分加成奖励';
        }

        if ($minPoints >= 2000) {
            $benefits[] = '专属客服通道';
            $benefits[] = '内容优先更新';
        }

        if ($minPoints >= 5000) {
            $benefits[] = '终身会员特权';
            $benefits[] = '专属定制服务';
        }

        // 根据等级名称添加特殊权益
        if (strpos($levelName, 'vip') !== false || strpos($levelName, '会员') !== false) {
            $benefits[] = 'VIP专属标识';
        }

        if (strpos($levelName, '钻石') !== false || strpos($levelName, 'diamond') !== false) {
            $benefits[] = '钻石会员专属';
        }

        // 每日浏览限制权益
        if (isset($level['daily_view_limit']) && $level['daily_view_limit'] > 0) {
            $benefits[] = "每日可浏览 {$level['daily_view_limit']} 篇内容";
        } else {
            $benefits[] = '无限制浏览';
        }

        return array_unique($benefits);
    }

    /**
     * 增强签到规则数据
     * @param array $signRules 原始签到规则
     * @return array
     */
    private function enhanceSignRules($signRules)
    {
        $enhanced = [];
        foreach ($signRules as $rule) {
            $enhanced[] = [
                'day'         => $rule['day'],
                'points'      => $rule['points'],
                'description' => "连续签到{$rule['day']}天可获得{$rule['points']}积分",
                'is_bonus'    => $rule['day'] == 7, // 第7天是奖励日
            ];
        }
        return $enhanced;
    }

    /**
     * 获取签到统计数据
     * @param int $userId 用户ID
     * @param string $month 月份
     * @return array
     */
    private function getSignStats($userId, $month)
    {
        $startDate = $month . '-01';
        $endDate   = date('Y-m-t', strtotime($startDate));
        $today     = date('Y-m-d');

        return [
            'total_days'              => UserSign::where('user_id', $userId)->count(),
            'month_days'              => UserSign::where('user_id', $userId)
                ->where('sign_date', '>=', $startDate)
                ->where('sign_date', '<=', $endDate)
                ->count(),
            'total_points'            => UserSign::where('user_id', $userId)->sum('points'),
            'month_points'            => UserSign::where('user_id', $userId)
                ->where('sign_date', '>=', $startDate)
                ->where('sign_date', '<=', $endDate)
                ->sum('points'),
            'max_continuous_days'     => UserSign::where('user_id', $userId)->max('continuous_days'),
            'current_continuous_days' => UserSign::getUserContinuousDays($userId),
        ];
    }

    /**
     * 计算今日可获得积分
     * @param int $continuousDays 当前连续签到天数
     * @param bool $todaySigned 今日是否已签到
     * @param array $signRules 签到规则
     * @return int
     */
    private function calculateTodayPoints($continuousDays, $todaySigned, $signRules)
    {
        if ($todaySigned) {
            // 已签到，返回今日获得的积分
            return UserSign::getTodayPoints($this->user_id);
        } else {
            // 未签到，计算签到后可获得的积分
            $nextDay = $continuousDays + 1;
            if ($nextDay > 7) {
                $nextDay = 1; // 超过7天重置为1
            }

            foreach ($signRules as $rule) {
                if ($rule['day'] == $nextDay) {
                    return $rule['points'];
                }
            }

            return 5; // 默认积分
        }
    }

    /**
     * 生成日历数据
     * @param array $signLogs 签到记录
     * @param string $month 月份
     * @return array
     */
    private function generateCalendarData($signLogs, $month)
    {
        $year     = (int) substr($month, 0, 4);
        $monthNum = (int) substr($month, 5, 2);

        // 获取当月第一天是星期几
        $firstDay = date('w', strtotime($month . '-01'));
        // 获取当月天数
        $daysInMonth = date('t', strtotime($month . '-01'));

        // 获取已签到的日期
        $signedDates = [];
        foreach ($signLogs as $log) {
            $signedDates[] = $log['sign_date'];
        }

        // 生成日历数据
        $calendar = [];
        $today    = date('Y-m-d');

        // 填充前面的空白
        for ($i = 0; $i < $firstDay; $i++) {
            $calendar[] = ['date' => null, 'day' => null, 'signed' => false, 'is_today' => false];
        }

        // 填充当月天数
        for ($day = 1; $day <= $daysInMonth; $day++) {
            $dateStr    = sprintf('%04d-%02d-%02d', $year, $monthNum, $day);
            $calendar[] = [
                'date'     => $dateStr,
                'day'      => $day,
                'signed'   => in_array($dateStr, $signedDates),
                'is_today' => $dateStr === $today,
            ];
        }

        return $calendar;
    }

    /**
     * 获取VIP权益列表
     * @return array
     */
    private function getVipBenefits()
    {
        return [
            [
                'icon'        => 'fas fa-crown',
                'title'       => '身份标识',
                'description' => '尊贵的VIP身份标识，彰显您的特殊地位'
            ],
            [
                'icon'        => 'fas fa-unlock',
                'title'       => '无限制浏览',
                'description' => '解锁所有付费内容，畅享无限制浏览体验'
            ],
            [
                'icon'        => 'fas fa-headset',
                'title'       => '专属客服',
                'description' => '7x24小时专属客服支持，问题快速解决'
            ],
        ];
    }

    /**
     * 获取VIP FAQ列表
     * @return array
     */
    private function getVipFaqList()
    {
        return [
            [
                'question' => '如何购买VIP会员？',
                'answer'   => '您可以在本页面选择适合您的VIP套餐，点击"立即购买"按钮，选择支付方式完成支付即可成为VIP会员。'
            ],
            [
                'question' => 'VIP会员有什么特权？',
                'answer'   => 'VIP会员可以免费查看所有付费内容，享受无限下载、专属客服、积分奖励等多项特权。'
            ],
            [
                'question' => 'VIP会员是否可以退款？',
                'answer'   => '一般情况下，VIP会员购买后不支持退款。如有特殊情况，请联系客服处理。'
            ],
            [
                'question' => 'VIP会员到期后会自动续费吗？',
                'answer'   => 'VIP会员到期后不会自动续费，需要您手动进行续费操作。'
            ],
            [
                'question' => '如何查看VIP到期时间？',
                'answer'   => '您可以在个人中心或本页面顶部查看VIP到期时间。'
            ],
            [
                'question' => 'VIP到期后会怎样？',
                'answer'   => 'VIP到期后将恢复为普通用户，之前下载的内容仍可正常使用。'
            ]
        ];
    }
}
